package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.heima.minio.service.FileStorageService;
import com.heima.utils.baidu.Base64Util;
import com.heima.utils.baidu.FileUtil;
import com.heima.utils.baidu.HttpUtil;
import com.heima.wemedia.service.BaiduScanService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author jack
 * @data 2024 10:19
 */
@Service
@Slf4j
public class BaiduScanServiceImpl implements BaiduScanService {

    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 百度云内容审核 - 审核文本
     *
     * @param text
     * @return
     */
    @Override
    public Map<String, Object> scanText(String text) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined";
        try {
            String param = "text=" + URLEncoder.encode(text, "utf-8");

            //先从缓存中取
            String accessToken = stringRedisTemplate.opsForValue().get("accessToken");
            if (StringUtils.isEmpty(accessToken)){
                //缓存没有再调用百度云接口获取
                accessToken = getAccessToken();
                //添加缓存
                stringRedisTemplate.opsForValue().set("accessToken",accessToken,10, TimeUnit.DAYS);
            }

            String result = HttpUtil.post(url, accessToken, param);
            System.out.println(result);
            return JSON.parseObject(result, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Map<String, Object> res = new HashMap<>();
        res.put("conclusionType", 3);        //如果调用百度云失败，走人工审核
        return res;
    }

    /**
     * 百度云内容审核 - 审核图片
     *
     * @param imgUrl
     * @return
     */
    @Override
    public Map<String, Object> scanImg(String imgUrl) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined";
        try {
            byte[] imgData = fileStorageService.downLoadFile(imgUrl);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            //先从缓存中取
            String accessToken = stringRedisTemplate.opsForValue().get("accessToken");
            if (StringUtils.isEmpty(accessToken)){
                //缓存没有再调用百度云接口获取
                accessToken = getAccessToken();
                //添加缓存
                stringRedisTemplate.opsForValue().set("accessToken",accessToken,10, TimeUnit.DAYS);
            }
            String result = HttpUtil.post(url, accessToken, param);
            System.out.println(result);
            return JSON.parseObject(result, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Map<String, Object> res = new HashMap<>();
        res.put("conclusionType", 3);        //如果调用百度云失败，走人工审核
        return res;
    }


    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
    private String getAccessToken(){
        try {
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "");
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/oauth/2.0/token?client_id=Dt5ErlDfV447gD90vPDG4rLZ&client_secret=n8gaYN40MVdCbGYaNlN7q2QqmWATGoEn&grant_type=client_credentials")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            return jsonObject.getString("access_token");
        }catch (Exception e){
            return null;
        }
    }
}
